<template>
  <el-card style="height: 600px;">
    <div slot="header" style="text-align: center;font-weight: bold;">{{ title }}</div>
      <el-form :inline="true">
        <el-input v-model="input" placeholder="请输入关键字查询文档"></el-input>
  
        <el-card>
        <el-button icon="el-icon-search" @click="queryName">根据文件名查询</el-button>
        <el-button icon="el-icon-search" @click="queryText">根据文本内容查询</el-button>
        <el-button icon="el-icon-search" @click="queryAll">查询全部</el-button>
        <el-select v-model="value" @change="queryType" placeholder="根据文件类型选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
        
      </el-select>
      <el-button type="danger" plain  @click="clear">清空</el-button>
    </el-card>
    
        <el-table
          :data="tableData"
          border
          style="width: 100%">
          <el-table-column
            prop="id"
            label="id"
            width="180">
          </el-table-column>
          <el-table-column
            prop="fileName"
            label="文件名"
            width="180">
          </el-table-column>
          <template>
  <el-table-column label="文件操作">
    <template slot-scope="scope">
      <a :href="scope.row.filePath" @click.prevent="handleFileAction(scope.row.filePath)">
        {{ getFileActionText(scope.row.filePath) }}
      </a>
    </template>
  </el-table-column>
</template>

      <el-table-column
            prop="type"
            label="文件类型">
            <template #default="scope">
      <div v-if="scope.row.type === '0'">重要文件</div>
      <div v-else-if="scope.row.type === '1'">图像文件</div>
      <div v-else-if="scope.row.type === '2'">文本文件</div>
      <div v-else-if="scope.row.type === '3'">视频文件</div>
      <div v-else>未知文件类型</div>
    </template>
          </el-table-column>
          <el-table-column label="文件内容">
    <template #default="scope">
      <a href="#" @click.prevent="viewFileContent(scope.row.text)">
        查看内容
      </a>
    </template>
    
  </el-table-column>

  <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" type="danger" @click="deleteFile(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
        </el-table>
        </el-form>
    
        <el-row>
                <el-col :span="24">
                    <!-- 放分页 -->
                    <el-pagination background :page-sizes="[4, 10, 20, 50]" :page-size="pageSize" :current-page="pageNum"
                        @next-click="nextPage" @prev-click="prevPage" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" layout=" total,sizes,prev, pager, next" :total="total">
                    </el-pagination>
                </el-col>
            </el-row>
  
    
  </el-card>
    </template>
      
    <script>
    import axios from 'axios';
    import { MessageBox } from 'element-ui';

    export default {
      data() {
        return {
          hotWords: ['商务', '经济', '信息'],
          fileUrl: '',
          loading:true,
          title: '文档查询',
          input: '',
          tableData: [],
          options: [{
              value: '0',
              label: '重要文件'
            }, {
              value: '1',
              label: '图像文件'
            }, {
              value: '2',
              label: '文本文件'
            }, {
              value: '3',
              label: '视频文件'
            }],
            value: '',
            pageNum: 1,
                pageSize: 4,
                total: 0,
            }
      },
      methods: {
        
        highlightHotWords(text) {
    const hotWords = this.hotWords;
    return hotWords.reduce((accText, word) => {
    const regex = new RegExp(`(${word})`, 'gi'); // 全局不区分大小写匹配
    return accText.replace(regex, (match, p1) =>`<span class="hot-word">${p1}</span>`);
  }, text);
},

handleFileAction(filePath) {
      // 如果文件是图片格式（.png, .jpg, .jpeg），则跳转到预览页面
      if (filePath.toLowerCase().endsWith('.png') || filePath.toLowerCase().endsWith('.jpg') || filePath.toLowerCase().endsWith('.jpeg')) {
        this.navigateToPreviewPage(filePath);
      } else {
        // 非图片文件，执行下载操作
        this.downloadFile(filePath);
      }
    },

    navigateToPreviewPage(filePath) {
      this.$router.push({ name: 'local', params: { filePath } });
    },

    downloadFile(filePath) {
      const link = document.createElement('a');
      link.href = filePath;
      link.download = ''; 
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    getFileActionText(filePath) {
      return filePath.toLowerCase().endsWith('.png') || filePath.toLowerCase().endsWith('.jpg') || filePath.toLowerCase().endsWith('.jpeg')
        ? '预览图片'
        : '下载文件';
    },
async viewFileContent(content) {
  const highlightedContent = this.highlightHotWords(content);

  
  const handleTextSelection = () => {
    const selectedText = window.getSelection().toString();
    if (selectedText) {
      
      console.log("选取到的文字:", selectedText);
    }
  };

  document.addEventListener('mouseup', handleTextSelection);

  MessageBox.confirm(highlightedContent, '文件内容', {
  confirmButtonText: '查询选中内容', 
  cancelButtonText: '取消',
  dangerouslyUseHTMLString: true,
  showCancelButton: true, 
  closeOnClickModal: false, 
}).then(() => {

  const selectedText = window.getSelection().toString();
  if (selectedText) {
    this.querySeText(selectedText);
  }
}).catch(() => {


});
},
        clear() {
        this.input = ''; 
        this.value = '';
        this.tableData = [];
      },
        prevPage(val) {
                this.pageNum = val;
                this.queryAll();
            },
            nextPage(val) {
                //点击下一页触发
    
                this.pageNum = val;
                this.queryAll();
            },
            queryCondition() {
                this.pageNum = 1;
                this.queryAll();
            },
            handleSizeChange(val) {
                //改变每页条数触发
                this.pageNum = 1;
                this.pageSize = val;
                this.queryAll();
            },
            handleCurrentChange(val) {
                this.pageNum = val;
                this.queryAll();
            },
  
        async queryAll() {
          let pageParam = {};
                pageParam.pageNum = this.pageNum;
                pageParam.pageSize = this.pageSize;
                pageParam.param = this.queryAll;
          try {
            const response = await axios.get('http://localhost:9999/queryAll',{
           params: {
           pageNum: this.pageNum,
           pageSize: this.pageSize,
      },
    }); 
    
            
                        this.tableData = response.data.list;
                        this.pageNum = response.data.pageNum;
                        this.pageSize = response.data.pageSize;
                        this.total = response.data.total;
                        console.log(this.tableData);
                    
          } catch (error) {
            console.error('查询所有数据时出错:', error);
          }
        },
    
    
    
    
        async queryName() {
          
          if (!this.input.trim()) {
        this.$message.warning('请输入文件名后再进行查询！');
        return; 
      }
  
      // 准备分页参数
    const pageParam = {
      pageNum: this.pageNum,
      pageSize: this.pageSize,
      fileName: this.input, // 添加文件名参数
    };
  
          try {
              const response = await axios.get('http://localhost:9999/queryByFileName', {
                params: pageParam,
            });
            
      if (response.data && response.data.list && response.data.pageNum && response.data.pageSize && response.data.total) {
        this.tableData = response.data.list;
        this.pageNum = response.data.pageNum;
        this.pageSize = response.data.pageSize;
        this.total = response.data.total;
        console.log(this.tableData);
      } else {
        console.error('API响应数据结构不符合预期');
      }
    } catch (error) {
      console.error('根据文件名查询时出错:', error);
    }
      },
      async queryTextWord(keyword) {
      if (!keyword.trim()) {
        this.$message.warning('请输入文件内容后再进行查询！');
        return; 
      }

      const pageParam = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        text: keyword, // 使用传入的参数
      };

      try {
        const response = await axios.get('http://localhost:9999/queryByFileTextWord', {
          params: pageParam,
        });

        if (response.data && response.data.list && response.data.pageNum && response.data.pageSize && response.data.total) {
          this.tableData = response.data.list;
          this.pageNum = response.data.pageNum;
          this.pageSize = response.data.pageSize;
          this.total = response.data.total;

          const relatedCount = response.data.total;

        this.$message({
        type: 'success',
        message: `${keyword}在列表中有${relatedCount}条数据。`
      });

          console.log(this.tableData);
        } else {
          console.error('API响应数据结构不符合预期');
        }
      } catch (error) {
        console.error('根据文件内容查询时出错:', error);
      }
    },

    async queryText() {
      if (!this.input.trim()) {
        this.$message.warning('请输入文件内容后再进行查询！');
        return; 
      }

      const pageParam = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        text: this.input, 
      };

      try {
        const response = await axios.get('http://localhost:9999/queryByFileText', {
          params: pageParam,
        });

        if (response.data && response.data.list && response.data.pageNum && response.data.pageSize && response.data.total) {
          this.tableData = response.data.list;
          this.pageNum = response.data.pageNum;
          this.pageSize = response.data.pageSize;
          this.total = response.data.total;
          console.log(this.tableData);
        } else {
          console.error('API响应数据结构不符合预期');
        }
      } catch (error) {
        console.error('根据文件内容查询时出错:', error);
      }
    },

    async querySeText(selectedText) {
    try {
        const response = await axios.post('http://localhost:9999/queryByFileSeText', { text: selectedText });

        if (response.data && response.data.list && response.data.pageNum && response.data.pageSize && response.data.total) {
            this.tableData = response.data.list;
            this.pageNum = response.data.pageNum;
            this.pageSize = response.data.pageSize;
            this.total = response.data.total;

            // 使用消息提示替代控制台打印
            this.$message({
                message: `查询到 ${this.total} 条信息`,
                type: 'success',
            });
        } else {
            this.$message.warning('选择的文件太长啦~~');
        }
    } catch (error) {
        console.error('根据文件内容查询时出错:', error);
    }
},
      async queryType() {
    
              try {
                  const response = await axios.get('http://localhost:9999/queryByFileType', {
                  params: {
                    type: this.value, 
                  },
                });
                 
               this.tableData = response.data;
               
              } catch (error) {
                console.error('根据文本内容查询时出错:', error);
              }
          },
  
          async deleteFile(id) {
        
        const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
  
        if (confirmResult !== 'confirm') {
          return; 
        }
  
        try {
          await axios.delete(`http://localhost:9999/deleteFile/${id}`);
          this.$message.success('文件删除成功');
  
          await this.queryAll();
        } catch (error) {
          console.error('删除文件时出错:', error);
          this.$message.error('文件删除失败，请重试');
        }
      },
    
    },
      methoud(){
        this.queryAll();
      }
    }
    </script>

<style>
.hot-word {
  color: blue; 
  cursor: pointer;
}
</style>